/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.sms.service;

import java.util.List;

import javax.persistence.Query;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.service.BaseService;
import com.chlitina.store.modules.sms.dao.StoreDiagnoseDao;
import com.chlitina.store.modules.sms.entity.StoreDiagnose;
import com.chlitina.store.modules.sys.entity.Store;

/**
 * 店面诊断结果Service
 * @author liujiang
 * @version 2013-08-01
 */
@Component
@Transactional(readOnly = true)
public class StoreDiagnoseService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(StoreDiagnoseService.class);
	
	@Autowired
	private StoreDiagnoseDao storeDiagnoseDao;
	
	public StoreDiagnose get(Long id) {
		return storeDiagnoseDao.findOne(id);
	}
	
	public StoreDiagnose getLastByStore(Store store) {
		DetachedCriteria dc = storeDiagnoseDao.createDetachedCriteria();
		if (store != null){
			dc.add(Restrictions.eq("store", store));
		}
		dc.getExecutableCriteria(storeDiagnoseDao.getSession()).setMaxResults(1);
		dc.addOrder(Order.desc("id"));
		List<StoreDiagnose> list =  storeDiagnoseDao.find(dc);
		if(list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	public Page<StoreDiagnose> find(Page<StoreDiagnose> page, Long storeId) {
		DetachedCriteria dc = storeDiagnoseDao.createDetachedCriteria();
		if (storeId != null){
			dc.add(Restrictions.eq("store.id", storeId));
		}
		dc.addOrder(Order.desc("diagnose_date"));
		return storeDiagnoseDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(StoreDiagnose storeDiagnose) {
		storeDiagnoseDao.save(storeDiagnose);
		storeDiagnoseDao.flush();
		Query query = storeDiagnoseDao.createSqlQuery("{call SP_CALC_STORE_SCORE(?)}", storeDiagnose.getId());
		query.executeUpdate();
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		storeDiagnoseDao.delete(id);
	}
}
